package com.mvd.app.ac2025;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac2020.VideoListAdapter;
import com.mvd.app.activity.BaseActivity;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.JsonUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.PdaVideoModel;
import com.mvd.app.model.VideoUploadModel;
import com.mvd.app.upload.MyUploadService;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;


public class HBVideo_UploadActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        ApiConfig, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.ac_video_listview)
    ListView acVideoListview;
    @BindView(R.id.ac_video_scrollview)
    ScrollView acVideoScrollview;
    private CarsInforModel carsInforModel;
    private HBVideo_UploadActivity instances = null;
    private String Login_name = "";//当前登录的检测员的名字
    private String waijian_chedao = null;//外检车道，检测线代号
    private VideoListAdapter videoListAdapter;
    private String video_type;//拍摄录像的类型
    private String Line = "1";//外检车道
    private List<PdaVideoModel> videoModelList, videoAdapterList;
    private VideoListAdapter videoAdapter;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_list);
        ButterKnife.bind(this);

        setTopTitle("环保视频");
        setBackBtn();

        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {//检查是否获取该权限
            UtilsLog.e("zzl=已获取权限");
        } else {
            UtilsLog.e("zzl=meiyou===权限");
            EasyPermissions.requestPermissions(this, "必要的权限", 0, PERMISSIONS);
        }
        String logStrf = "\n" + "onCreate---环保--视频列表-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        instances = this;
//        waijian_chedao = getIntent().getExtras().getString("CarDetailsActivity_acCarDetailsWaijianchedao", "");
        carsInforModel = (CarsInforModel) getIntent().getSerializableExtra
                ("model_CarsInforModel223");
        UtilsLog.e("carsInforModel=55=" + carsInforModel.toString());
//        carsInforModel = getIntent().getExtras().getParcelable("CarDetailsActivity_CarsInforModel");
        Login_name = getIntent().getExtras().getString("Login_name", "");
        UtilsLog.e("Login_name=Login_name=" + Login_name);
//        Line = getIntent().getStringExtra("CarDetailsActivity_Line");
//        getVideoItems();

        initVideo();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        Log.e("tag", "onRequestPermissionsResult:" + "== requestCode:" + requestCode +
                "===permissions==" + permissions.length +
                "===grantResults==" + grantResults.length);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    void initVideo() {
        videoAdapterList = new ArrayList<PdaVideoModel>();
        PdaVideoModel model = null;
        for (int i = 0; i < 1; i++) {
            model = new PdaVideoModel();
            model.setItemName("环保视频");
            model.setItemCode("pda_hb");
            videoAdapterList.add(model);
//        if (videoModelList.get(i).getItemCode().contains("PDA")) {
//            videoAdapterList.add(videoModelList.get(i));
//        }
        }

        if (videoAdapterList != null && videoAdapterList.size() > 0) {
            videoAdapter = new VideoListAdapter(instances, videoAdapterList, mListener);
            acVideoListview.setAdapter(videoAdapter);
            setListViewHeightBasedONChildren(acVideoListview);
        }
    }

    private void getVideoItems() {
        UtilsLog.e("getVideoItems---url==" + SharedPreferencesUtils.getIP(this) + VIDEO_LIST);
        String logStr = "\n" + "外检--getVideoItems--请求" +
                "\n" + "URL::" + SharedPreferencesUtils.getIP(instances) +
                VIDEO_LIST;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>get(SharedPreferencesUtils.getIP(this) + VIDEO_LIST).tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        String logStr3 = "\n" + "外检--getVideoItems--onSuccess" +
                                "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("getVideoItems-newResult==" + newResult);
                        videoModelList = new ArrayList<PdaVideoModel>();
                        videoAdapterList = new ArrayList<PdaVideoModel>();
                        if (!TextUtils.isEmpty(newResult) && !"[[]]".equals(newResult) && !"[{}]".equals
                                (newResult) && !"[]".equals(result)) {
                            videoModelList = JsonUtil.stringToArray(newResult,
                                    PdaVideoModel[].class);
                            if (videoModelList != null && videoModelList.size() > 0) {
                                for (int i = 0; i < videoModelList.size(); i++) {
                                    if (videoModelList.get(i).getItemCode().contains("PDA")) {
                                        videoAdapterList.add(videoModelList.get(i));
                                    }
                                }
                                if (videoAdapterList != null && videoAdapterList.size() > 0) {
                                    videoAdapter = new VideoListAdapter(instances, videoAdapterList, mListener);
                                    acVideoListview.setAdapter(videoAdapter);
                                    setListViewHeightBasedONChildren(acVideoListview);
                                }
                            } else {

                                UtilsLog.e("getVideoItems-Result==没有获取到当前车辆视频的项目");
                            }
                        } else {
                            UtilsLog.e("getVideoItems-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("getVideoItems-onError==" + response.body());
                        CommonUtils.hideLoadingDialog(instances);
                        String logStrf = "\n" + "外检--getVideoItems--请求失败--error" +
                                "\n" + "result::" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
                    }
                });
    }

    /**
     * 实现类，响应按钮点击事件
     */
    PdaVideoModel typeModel;
    int TypeModel_Position = 0;
    String item_code = "";
    private VideoListAdapter.MyClickListener mListener = new VideoListAdapter.MyClickListener() {
        @Override
        public void myOnClick(int position, View v, int flag) {
            video_type = videoAdapterList.get(position).getVideoType();
            TypeModel_Position = position;
            typeModel = new PdaVideoModel();
            typeModel.setItemName(videoAdapterList.get(position).getItemName());
            typeModel.setItemCode(videoAdapterList.get(position).getItemCode());
            item_code = videoAdapterList.get(position).getItemCode();
//            Intent intent_video_1 = new Intent(instances, VideoRecorderActivity.class);
//            intent_video_1.putExtra("CarDetailsActivity_CarsInforModel", carsInforModel);
//            intent_video_1.putExtra("CarDetailsActivity_acCarDetailsWaijianchedao",
//                    waijian_chedao);
//            intent_video_1.putExtra("video_type", video_type);
//            intent_video_1.putExtra("item_code", videoAdapterList.get(position).getItemCode());
//            intent_video_1.putExtra("CarDetailsActivity_Line", Line);
//            startActivityForResult(intent_video_1, 666);
            Video_start_time = DateUtil.currentTime2();
            UpVideo_ok = false;
            saveVideo();
        }
    };
    String filePath = "", current_videoPath = "";

    void saveVideo() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String logStr = "\n" + "环保视频外检上传视频--校验存储空间--成功---" + "\n";
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());

            String timeStamp = String.valueOf(System.currentTimeMillis());
//          filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + timeStamp+".mp4";
            filePath = Environment.getExternalStorageDirectory() + "/myvideo/";
            File mediaStorageDir = new File(filePath);
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    UtilsLog.e("环保视频视频路径--文件夹创建失败");
                    String logStr22 = "\n" + "环保视频视频路径--文件夹创建失败---" + "\n" + filePath + "\n";
                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
                    return;
                }
            }
            String videoPath = filePath + timeStamp + ".mp4";
            current_videoPath = videoPath;
            UtilsLog.e("环保视频视频路径=videoPath==" + videoPath);
            String logStr22 = "\n" + "环保视频视频路径--成功---" + "\n" + videoPath + "\n";
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
//                String filePath = FileManager.get().getRootFile() + "/msc/"  + "111111.mp4";   // 保存路径
//            Uri uri = Uri.fromFile(new File(videoPath));   // 将路径转换为Uri对象
//            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  // 表示跳转至相机的录视频界面
//            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
//
//            //大小限制是long型，int 型无效，所以后边要写一个L
////            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 60 * 10 * 1024 * 1024L);//限制录制大小(10M=10 * 1024 * 1024L)
//
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);    // 表示录制完后保存的录制，如果不写，则会保存到默认的路径，在onActivityResult()的回调，通过intent.getData中返回保存的路径
//            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60 * 10);   // 设置视频录制的最长时间
//            startActivityForResult(intent, 666);  // 跳转

            startVideo();


        } else {
            String logStr = "\n" + "环保视频外检上传视频--校验存储空间--失败" + "\n";
            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        }
    }

    boolean UpVideo_ok = false;
    Uri Uri;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UtilsLog.e("requestCode==" + requestCode);
        if (data != null) {
            if (requestCode == 666) {
                Video_End_time = DateUtil.currentTime2();
                Uri = data.getData();
                UtilsLog.e("Uri.toString()==" + Uri.toString());
                UtilsLog.e("Uri.getPath()==" + Uri.getPath());
                String logStr22 = "\n" + "环保视频视频路径--onActivityResult-data---Uri.getPath()---" + "\n" + Uri.getPath() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());

                runnable = new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = Uri.getPath();
//                        message.obj =current_videoPath;
                        handlerUI.sendMessage(message);
//                            handler_zhaungsuji.postDelayed(runnable_zhuangsuji, 1 * 1000);
                    }
                };
                handlerUI.post(runnable);


//                getDataUploadVideo(new File(Uri.getPath()));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //撤销定时器
        handlerUI.removeCallbacks(runnable);
        OkGo.getInstance().cancelTag(this);
        String logStrf = "\n" + "onDestroy---环保视频--视频列表-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        instances = null;
    }

    //运行在主线程的Handler：使用Android默认的UI线程中的Looper
    public Handler handlerUI = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    CommonUtils.showLoadingDialog(instances, "录像完成");
//                    compressVideo(Uri.getPath());
//                    compressVideo(current_videoPath);
                    compressVideo(mVideoPath);
                    break;
            }
        }
    };

    private Runnable runnable;
    String videoPath = "";

    String compressVideo(String videoUriString) {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String compressFilePath = "";
//          filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + timeStamp+".mp4";
//        String filePath = Environment.getExternalStorageDirectory() + "/myvideo/compress/";
        String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/myvideo/compress/";
        File mediaStorageDir = new File(filePath);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                UtilsLog.e("视频路径-compress-文件夹创建失败");
                String logStr22 = "\n" + "环保视频视频路径--文件夹创建失败-compress--" + "\n" + filePath + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
            }
        }
        videoPath = filePath + timeStamp + ".mp4";
        UtilsLog.e("视频路径=videoPath=compress=" + videoPath);
//        String videoPath = filePath + timeStamp + ".mp4";
//        UtilsLog.e("视频路径=videoPath=compress=" + videoPath);


        VideoUploadModel model = new VideoUploadModel();
        model.setTimes(carsInforModel.getTimes());
        model.setPlatformSN(carsInforModel.getPlatformSN());
//        model.setVideoType("pda");
//        model.setItemCode("");
        model.setCarNO(carsInforModel.getPlateRegion()
                + carsInforModel.getPlateNO());
//        model.setCarNO(carsInforModel.getPlateNO());
        model.setPlateType(carsInforModel.getPlateType());
        model.setLine("1");
        model.setVIN(carsInforModel.getVIN());
        model.setZp(videoPath);
        model.setStartTime(Video_start_time);
        model.setEndTime(Video_End_time);
        model.setPath(SharedPreferencesUtils.getHuanBaoIP(instances) + HB_VIDEO_UP);
        model.setSize(videoUriString);
        model.setStatement("0");
        model.save();
        startService(model);

        String logStr22 = "\n" + "环保视频视频路径=videoPath=compress=--" + "\n" + videoPath + "\n" +
                "VideoUploadModel==" + model.toString();
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
//        try {
//            ZipUtils.ZipFolder(videoUriString,videoPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        /**
         * @param srcPath     string, filepath of source file
         * @param destPath    string, ouput filepath
         * @param outputWidth  pixels, output video width
         * @param outputHeight pixels, output video height
         * @param bitrate  int, in bits per second 200 * 360 * 30
         * @param listener  the listenr of convert progress
         */
//        VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 800,  200 * 360 * 30, new VideoSlimmer.ProgressListener() {
//            @Override
//            public void onStart() {
//                //convert start
//                CommonUtils.showLoadingDialog(instances, "视频压缩中...");
//            }
//
//            @Override
//            public void onFinish(boolean result) {
//                UtilsLog.e("视频路径=onFinish=" + result);
//                CommonUtils.hideLoadingDialog(instances);
//                //convert finish,result(true is success,false is fail)
////                CommonUtils.showLoadingDialog(instances, "视频压缩完成");
//                getDataUploadVideo(new File(videoPath));
//            }
//
//
//            @Override
//            public void onProgress(float percent) {
//                UtilsLog.e("视频路径=onProgress=" + percent);
////                CommonUtils.showLoadingDialog(instances, "视频压缩中：" + percent);
//            }
//        });
        CommonUtils.hideLoadingDialog(instances);
        typeModel.setColor(1);
        videoAdapterList.set(TypeModel_Position, typeModel);
        videoAdapter.notifyDataSetChanged();
        return compressFilePath;
    }

    //开启服务
    public void startService(VideoUploadModel model) {
        //开启服务需要Intent对象,和Activity跳转类似
        Intent intent = new Intent(this, MyUploadService.class);
        intent.putExtra("service_model", model);
        startService(intent);
    }

    private String Video_start_time = "", Video_End_time = "";//录像开始时间，结束时间

    //上传视频
    private void getDataUploadVideo(final File file) {
        UtilsLog.e("上传视频---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_VIDEO);
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_VIDEO).tag(instances)
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", video_type)
                .params("ItemCode", item_code)
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getPlateNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", waijian_chedao)
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", file)
                //开始时间
                .params("StartTime", Video_start_time)
                //结束时间
                .params("EndTime", Video_End_time)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("上传视频-result==" + result);
                        String logStr = "\n" + "外检上传视频--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_VIDEO + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            Logger.d("上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UpVideo_ok = true;
//                                Intent i = new Intent();
//                                Bundle bundle = new Bundle();
//                                bundle.putString("result", "1");
//                                setResult(666, i.putExtras(bundle));
//                                finish();
                                Toast.makeText(instances, "上传录像成功", Toast.LENGTH_LONG).show();
                            } else {
                                UpVideo_ok = false;
                                String logStr2 = "\n" + "外检上传视频--失败" +
                                        "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                        UPLOAD_VIDEO + "\n" + "result:" + response.body() + "\n";
                                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
                                Toast.makeText(instances, "上传录像失败，请重新拍摄", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            UpVideo_ok = false;
                            String logStr3 = "\n" + "上传视频--失败" +
                                    "\n" + "data::" + "没有数据" + "\n" + "result:" + response.body() + "\n";
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
                            UtilsLog.e("上传视频-result==" + "没有数据");
                        }
                        if (UpVideo_ok) {
                            typeModel.setColor(1);
                        } else {
                            typeModel.setColor(0);
                        }
                        videoAdapterList.set(TypeModel_Position, typeModel);
                        videoAdapter.notifyDataSetChanged();
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UpVideo_ok = false;
                        UtilsLog.e("上传视频-onError==" + response.body());
                        UtilsLog.e("上传视频-onError==" + response.getException());
                        String logStr = "\n" + "上传录像视频-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_VIDEO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    /**
     * 内容提供者和XML配置一样
     */
    String fileProvider = "com.mvd.hangzhou.fileprovider";
    /**
     * 启动相机，创建文件，并要求返回uri
     */
    private Uri mVideoUri;
    private Uri mImageUri;
    File mVideoFile;
    String mVideoPath;
    private String mVideoName;
    private String mImageName;
    private String mImagePath;
    private File mImageFile;

    private void startVideo() {
        Intent intent = new Intent();
        //指定动作，启动相机
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        UtilsLog.e("指定启动相机动作，完成。");
        //创建文件
        createVideoFile();
        UtilsLog.e("创建视频文件结束。");
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        UtilsLog.e("添加权限。");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //做一些处理
            //获取uri
            mVideoUri = FileProvider.getUriForFile(this, fileProvider, mVideoFile);
        } else {
            //在版本低于此的时候，做一些处理
            mVideoUri = Uri.fromFile(mVideoFile);
        }

        UtilsLog.e("根据视频文件路径获取uri。");
        //将uri加入到额外数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
        UtilsLog.e("将uri加入启动相机的额外数据。");
        UtilsLog.e("启动相机...");
        //启动相机并要求返回结果
        startActivityForResult(intent, 666);
        UtilsLog.e("拍摄中...");
    }

    /**
     * 创建视频文件
     */
    private void createVideoFile() {
        UtilsLog.e("开始创建图片文件...");
        //设置图片文件名（含后缀），以当前时间的毫秒值为名称
        mVideoName = Calendar.getInstance().getTimeInMillis() + ".mp4";
        UtilsLog.e("设置图片文件的名称为：" + mVideoName);
        //创建图片文件
        mVideoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/myvideo/", mVideoName);
        //将图片的绝对路径设置给mImagePath，后面会用到
        mVideoPath = mVideoFile.getAbsolutePath();
        //按设置好的目录层级创建
        mVideoFile.getParentFile().mkdirs();
        UtilsLog.e("按设置的目录层级创建图片文件，路径：" + mVideoPath);
        //不加这句会报Read-only警告。且无法写入SD
        mVideoFile.setWritable(true);
        UtilsLog.e("将图片文件设置可写。");
    }
}
